package com.scut.online_black_market.service.impl;

import com.scut.online_black_market.entity.ProductSellout;
import com.scut.online_black_market.entity.ShoppingGuide;
import com.scut.online_black_market.exception.UniversalException;
import com.scut.online_black_market.mapper.ProductSelloutMapper;
import com.scut.online_black_market.mapper.ShoppingGuideMapper;
import com.scut.online_black_market.service.ProductOffShelfService;
import com.scut.online_black_market.utility.JwtUtil;
import io.jsonwebtoken.Jwt;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class ProductOffShelfServiceImpl implements ProductOffShelfService {

    @Resource
    private ProductSelloutMapper productSelloutMapper;

    @Resource
    private ShoppingGuideMapper shoppingGuideMapper;

    @Resource
    private HttpServletRequest httpServletRequest;

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public void OffShelfProduct(int id) throws UniversalException {
        String studentNumber = jwtUtil.extractStudentNumber(httpServletRequest);

        ProductSellout productSellout = productSelloutMapper.selectById(id);

        if (productSellout == null) {
            throw new UniversalException("该商品不存在");
        }
        if (!studentNumber.equals(productSellout.getSellmanId())){
            throw new UniversalException("下架失败");
        }
        productSellout.setProductStatus(0);
        if (productSelloutMapper.updateById(productSellout) != 1) {
            throw new UniversalException("商品下架失败，请重试！");
        }

    }

    @Override
    public void OffShelfShoppingGuide(int id) throws UniversalException {
        String studentNumber = jwtUtil.extractStudentNumber(httpServletRequest);

        ShoppingGuide shoppingGuide = shoppingGuideMapper.selectById(id);
        if (shoppingGuide == null) {
            throw new UniversalException("商品不存在");
        }
        if (!studentNumber.equals(shoppingGuide.getShoppingGuideBuyerId())){
            throw new UniversalException("下架失败");
        }
        shoppingGuide.setShoppingGuideProductStatus(0);
        if (shoppingGuideMapper.updateById(shoppingGuide) != 1) {
            throw new UniversalException("求购下架失败，请重试！");
        }
    }
}
